package sql

import (
	"database/sql"
	"fmt"

	// 导入包，导入前缀为下划线，则init函数被执行，然后注册驱动。
	_ "github.com/mattn/go-sqlite3"
)

var db *sql.DB
var err error

// 连接数据库
func ConnectDB() {
	// Open() 函数指定驱动名称和数据源名称
	db, err = sql.Open("sqlite3", "./utils/sql/data.db")
	if err != nil {
		fmt.Printf("数据库创建失败: %v\n", err)
		return
	}
	// 调用db.Close() 函数，确保关闭数据库并阻止启动新的查询
	// defer db.Close()

	/* var version string
	// QueryRow() 执行查询，返回版本号
	err = db.QueryRow("SELECT SQLITE_VERSION()").Scan(&version)
	if err != nil {
		fmt.Printf("Database creation failed: %v\n", err)
		return
	}
	// 连接成功，打印出"database connected：版本号"
	fmt.Printf("Database creation successful: %v\n", version) */
}

// 插入数据
func Insert(query string, params ...interface{}) int {
	// 插入语句
	// res, err := db.Exec("INSERT INTO express_orders(uid, weight) VALUES(?,?)", uid, weight)
	_, err := db.Exec(query, params...)
	if err != nil {
		fmt.Printf("Insert data failed: %v\n", err)
		return 0
	}
	return 1
}

// 插入数据返回 ID
func InsertGetId(query string, params ...interface{}) int {
	res, err := db.Exec(query, params...)
	if err != nil {
		fmt.Printf("Insert data failed: %v\n", err)
		return 0
	}
	// 获取自增ID
	lastInsertId, _ := res.LastInsertId()
	return int(lastInsertId)
}

// 删除数据
func Delete(query string, params ...interface{}) int {
	// ret, err := db.Exec("delete from user where id=?;", id)
	ret, err := db.Exec(query, params...)
	if err != nil {
		fmt.Printf("delete failed, err:%v\n", err)
		return 0
	}

	var errs error
	_, errs = ret.RowsAffected()
	if err != nil {
		fmt.Printf("get lastinsert ID failed, err:%v\n", errs)
		return 0
	}
	return 1
}

// 更新数据
func Update(query string, params ...interface{}) int {
	// ret, err := db.Exec("update user set name=? where uid=?;", "tt", 12)
	ret, err := db.Exec(query, params...)
	if err != nil {
		fmt.Printf("update failed, err:%v\n", err)
		return 0
	}

	var errs error
	_, errs = ret.RowsAffected()
	if err != nil {
		fmt.Printf("get lastinsert ID failed, err:%v\n", errs)
		return 0
	}
	return 1
}

// 查询一条数据
func First(query string, params ...interface{}) {

}

// 查询数据
func Select(query string, params ...interface{}) (*sql.Rows, error) {

	// 查询语句
	// rows, err := db.Query("SELECT weight FROM express_orders WHERE uid = ?", uid)
	rows, err := db.Query(query, params...)
	if err != nil {
		fmt.Printf("Select查询失败: %v\n", err)
		return nil, err
	}

	return rows, err
}
